/*********************************************************************************
 *      Copyright:  (C) 2024 dengleen
 *                  All rights reserved.
 *
 *       Filename:  led.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(08/05/24)
 *         Author:  dengleen <dengleen@outlook.com>
 *      ChangeLog:  1, Release initial version on "08/05/24 15:01:25"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <gpiod.h>
#include <signal.h>
#include <unistd.h>

#include "led.h"
//#include "logger.h"

int g_stop = 0;
struct gpiod_chip         *chip;

led_gpio_t leds[LED_MAX] =
{
	{LED_R, 13, "red",   NULL},
	{LED_G, 19, "green", NULL},
	{LED_B, 26, "blue",  NULL},
};


// 信号处理函数，用于捕获 Ctrl+C 信号
void signal_handler(int signum) {
    if (signum == SIGINT) {
        g_stop = 1;
    }
}

void turn_led(int which, int status)
{
	if( which<0 || which >= LED_MAX )
		return ;

//	log_debug("turn %5s led GPIO#%d %s\n", leds[which].desc, leds[which].gpio, status?"on":"off");

	if( OFF == status)
		gpiod_line_set_value(leds[which].line, 0);
	else
		gpiod_line_set_value(leds[which].line, 1);
}

void blink_led(int which)
{
	if( which<0 || which >= LED_MAX )
		return ;

	turn_led(which, ON);
	sleep(BLINK_T);

	turn_led(which, OFF);
	sleep(BLINK_T);
}
int led_init()
{
	const char                *chipname = "gpiochip0";
	//struct gpiod_chip         *chip;
	int                        i;

	chip = gpiod_chip_open_by_name(chipname);
	if( !chip )
	{
//		log_error("gpiod open '%S' failed: %S\n", chipname, strerror(errno));
		return -1;
	}

	for(i=0; i<LED_MAX; i++)
	{
		leds[i].line = gpiod_chip_get_line(chip, leds[i].gpio);

		gpiod_line_request_output(leds[i].line, "rgbled", 0);
	}

	return 0;
}

int led_release()
{
	int     i;

	for(i=0; i<LED_MAX; i++)
	{
		turn_led(i, OFF);
		gpiod_line_release(leds[i].line);
	}

	gpiod_chip_close(chip);

	return 0;
}

int main()
{
	// 注册信号处理函数
    signal(SIGINT, signal_handler);

    // 初始化 LED
    if (led_init() != 0) {
        fprintf(stderr, "LED initialization failed.\n");
        return -1;
    }

    printf("LED is blinking. Press Ctrl+C to stop.\n");

    // 循环闪烁 LED
    while (!g_stop) {
        for (int i = 0; i < LED_MAX; i++) {
            blink_led(i);
        }
    }

    // 释放 LED 资源
    led_release();

    printf("Program exited successfully.\n");
    return 0;
}

